/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

package com.huawei.api.utils;

import com.huawei.api.bean.CloudDefect;
import com.huawei.api.bean.Defect;
import com.huawei.api.exception.DataConvertException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 报告工具类
 *
 * @since 2023/10/18
 */
public class ReportUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReportUtil.class);

    /**
     * 将报告插件缺陷列表
     *
     * @param content 内容
     * @return 缺陷列表
     * @throws DataConvertException 异常
     */
    public static List<Defect> getDefectsByContent(String content) throws DataConvertException {
        List<Defect> defects = new ArrayList<>();
        try {
            if (StringUtils.isNotBlank(content)) {
                defects = JSON.parseArray(content, Defect.class);
            }
        } catch (Exception exception) {
            LOGGER.debug("some error occur in report util, parse json error");
            throw new DataConvertException("parse json error");
        }
        return defects;
    }

    /**
     * 将报告结果转化为华为云的缺陷列表
     *
     * @param content 报告内容
     * @return List<CloudDefect> 缺陷列表
     */
    public static List<CloudDefect> getCloudDefectsByContent(String content) throws DataConvertException {
        List<CloudDefect> cloudDefects = new ArrayList<>();
        try {
            if (StringUtils.isNotBlank(content)) {
                cloudDefects = JSON.parseArray(content, CloudDefect.class);
            }
        } catch (Exception exception) {
            LOGGER.debug("some error occur in report util, parse json error");
            throw new DataConvertException("parse json error");
        }
        return cloudDefects;
    }

    public static void writeReport(Collection<CloudDefect> defects, String outputFile) throws DataConvertException {
        String jsonStr = JSONObject.toJSONString(defects);
        try (BufferedWriter bufferedWriter = new BufferedWriter(
            new OutputStreamWriter(Files.newOutputStream(FileUtils.getFile(outputFile).toPath()),
                StandardCharsets.UTF_8))) {
            bufferedWriter.write(jsonStr);
        } catch (IOException e) {
            LOGGER.error("write report error is {}", e.getMessage());
            throw new DataConvertException("write report error");
        }
    }
}
